<template>
  <el-dialog title="用户信息" v-model="visible" @update:model-value="close()">
    <el-select class="pf-mr-10" @change="tenantChangeEvent" v-model="formData.tenId">
      <el-option
        v-for="(t, index) in formData.tenants"
        :key="index"
        :label="t.name"
        :value="t.id"
        >{{ t.name }}</el-option
      >
    </el-select>
    <el-select v-model="formData.appId">
      <el-option
        v-for="(t, index) in formData.apps"
        :key="`app_${index}`"
        :label="t.appName"
        :value="t.id"
        >{{ t.appName }}</el-option
      >
    </el-select>
    <template #footer>
      <div class="pf-text-right">
        <el-button type="primary" @click="confirmChange">确认</el-button>
        <el-button @click="close()">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, reactive, ref, Ref, toRefs, watch } from 'vue';
import { useNotice } from '@/components/element-plus/notice';
import store from '@/store';
import { CommonResult, ResponseCodeEnum, useHttpClient } from 'pf-component';
import { systemApi } from '@/constants/api/system-api';

export default defineComponent({
  name: 'TenantAppDialog',
  props: {
    show: {
      type: Boolean,
      default: () => {
        return false;
      }
    }
  },
  emits: ['close', 'change'],
  setup(props, { emit }) {
    const { message } = useNotice();
    const show: Ref<boolean> = toRefs(props).show;

    const currentTenId = store.getters.currentTenId;
    const currentAppId = store.getters.currentAppId;
    const formData: {
      tenId: string;
      appId: string;
      apps: any[];
      tenants: any[];
    } = reactive({
      tenId: currentTenId,
      appId: currentAppId,
      apps: store.getters.apps,
      tenants: store.getters.tenants
    });

    const confirmChange = () => {
      close(true);
    };
    const cancel = () => {
      emit('close');
    };
    const close = (ok?: boolean) => {
      emit('close', ok);
      if (ok) {
        emit('change', { ...formData });
      }
    };

    const tenantChangeEvent = () => {
      useHttpClient()
        .general(systemApi.appApi.listByTenId, { tenId: formData.tenId })
        .then((res: CommonResult<any[]>) => {
          if (res.code === ResponseCodeEnum.SUCCESS) {
            formData.apps = res.data;
          } else {
            formData.apps = [];
          }
        });
    };
    const visible = ref(false);
    watch(show, () => {
      visible.value = show.value;
    });
    onMounted(() => {});

    return {
      visible,
      formData,
      currentTenId,
      confirmChange,
      cancel,
      close,
      tenantChangeEvent
    };
  }
});
</script>

<style scoped></style>
